package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 59. 螺旋矩阵 II
 * @date 2025/5/11 12:03
 */
public class E59 {

    /**
     * <h3>方法一：使用方向数组</h3>
     *
     * @param n 矩阵的边长
     * @return 矩阵
     */
    public int[][] generateMatrix(int n) {
        int[][] table = new int[n][n];
        boolean[][] visited = new boolean[n][n];
        int i = 0, j = 0, round = 0;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        for (int num = 1; num <= n * n; num++) {
            table[i][j] = num;
            visited[i][j] = true;
            i += directions[round][0];
            j += directions[round][1];
            if (i < 0 || j < 0 || i >= n || j >= n || visited[i][j]) {
                i -= directions[round][0];
                j -= directions[round][1];
                round = (round + 1) & 3;
                i += directions[round][0];
                j += directions[round][1];
            }
        }
        return table;
    }
}
